﻿using UnityEngine;
using System.Collections;

public class Angle : MonoBehaviour {


	GameObject  m_player;
	Transform m_transform;
	Rigidbody2D rigid;
    float RotateSpeed = 5;
    float ang = 0;
	void Start () {
		m_player = GameObject.FindGameObjectWithTag("Player");
		m_transform = this.transform;
	}

	void Update () {
        m_transform.Translate(new Vector3(0, 4 * Time.deltaTime, 0));
        RotateTo();
	}

    void RotateTo()
    {
        //判断目标敌人是否为空
       // if (mTarget == null) return;
        //计算要旋转到敌人方向的角度
        Vector3 mPos1 = m_transform.position;
        Vector3 mPos2 = m_player.transform.position;
        Vector3 mDir = (mPos2 - mPos1).normalized;
        //使得两向量共面
        mDir.z = 0;
        //计算两向量角度
        float mAngle = getAngle(Vector3.up, mDir);
        this.huanchong(mAngle);
        Vector3.Slerp(Vector3.up, mDir, 1);
        m_transform.eulerAngles = new Vector3(0, 0, ang) *1;

    }

    private float getAngle(Vector3 v1, Vector3 v2)
    {
        float mDot = Vector3.Dot(v1, v2);
        float mv1 = Mathf.Sqrt(v1.x * v1.x + v1.y * v1.y + v1.z * v1.z);
        float mv2 = Mathf.Sqrt(v2.x * v2.x + v2.y * v2.y + v2.z * v2.z);
        if (v2.x > v1.x)
        {
            return -Mathf.Acos(mDot / (mv1 * mv2)) * Mathf.Rad2Deg;
        }
        else
        {
            return Mathf.Acos(mDot / (mv1 * mv2)) * Mathf.Rad2Deg;
        }
    }

    //缓冲函数
    private void huanchong(float angle)
    {
       // if (ang <= angle)
       // {
            ang += Time.deltaTime*100;
            if (ang >= angle)
            {
                ang = angle;
            }
       // }
      //  if (ang > angle)
      //  {
      //      ang -= 1;
      //      if (ang <= angle)
      //      {
      //          ang = angle;
       //     }
      //  }
    }
}
